package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ApCollectionBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.thread.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP收藏   服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ApCollectionBehaviorServiceImpl implements ApCollectionBehaviorService {


    private final CacheService cacheService;


    /**
     * 收藏与取消收藏
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collectionBehavior(CollectionBehaviorDto dto) {

        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //2.判断用户是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3. 0文章    1动态

        //收藏的是文章
        if (dto.getType() == 0) {

            //0收藏    1取消收藏
            if (dto.getOperation() == 0) {

                //收藏文章
                log.info("保存当前key:{} ,{}, {}", dto.getEntryId(), user.getId(), dto);
                cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(),dto.getEntryId().toString(), JSON.toJSONString(dto));

            } else {
                //取消收藏文章
                log.info("删除当前key:{} ,{}, {}", dto.getEntryId(), user.getId(), dto);
                cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(),dto.getEntryId().toString());
            }

        } else if (dto.getType() == 1) {

            //TODO  动态
            log.info("动态");

            //0收藏    1取消收藏
            if (dto.getOperation() == 0) {

                //收藏文章
                log.info("保存当前key:{} ,{}, {}", dto.getEntryId(), user.getId(), dto);
                cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR_DYNAMIC + user.getId(),dto.getEntryId().toString(), JSON.toJSONString(dto));

            } else {
                //取消收藏文章
                log.info("删除当前key:{} ,{}, {}", dto.getEntryId(), user.getId(), dto);
                cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR_DYNAMIC + user.getId(),dto.getEntryId().toString());
            }

        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}